<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { QTable } from '@meetjs/element-plus-kit'
import { useDict } from '@/composables/useDict'
import { ChangeType } from '@/api/athlete/change/types'
import { tableColumns } from './config'
import type { ChangeHistoryRecord, ChangeHistoryProps, DictOption } from './types'

// 组件Props定义
const props = withDefaults(defineProps<ChangeHistoryProps>(), {
	readonly: true,
	data: () => []
})

// 使用字典和单位级联数据
const { dicts, registerOrgOptions } = useDict([
	'comp_athlete_project' // 注册项目字典
])

// 响应式数据
const loading = ref(false)

/**
 * 将级联组织数据转换为平铺字典格式
 */
const flatOrgOptions = computed<DictOption[]>(() => {
	const flattenOptions = (options: any[]): DictOption[] => {
		const result: DictOption[] = []

		options.forEach(option => {
			// 添加当前节点
			if (option.value && option.label) {
				result.push({
					label: option.label,
					value: option.value
				})
			}

			// 递归处理子节点
			if (option.children && Array.isArray(option.children)) {
				result.push(...flattenOptions(option.children))
			}
		})

		return result
	}

	return flattenOptions(registerOrgOptions.value || [])
})

/**
 * 根据字典值获取显示标签
 * @param dictValue 字典值
 * @param changeType 变更类型
 */
const getDictLabel = (dictValue: number, changeType: ChangeType): string => {
	if (changeType === ChangeType.ORG_CHANGE) {
		// 单位变更，使用单位字典
		const orgOption = flatOrgOptions.value.find(item => item.value === dictValue)
		return orgOption?.label || dictValue.toString()
	} else if (changeType === ChangeType.PROJECT_CHANGE) {
		// 项目变更，使用项目字典
		const projectOption = dicts.comp_athlete_project.value.find((item: any) => item.value === dictValue)
		return projectOption?.label || dictValue.toString()
	}

	return dictValue.toString()
}

const transformerData = (data: ChangeHistoryRecord[]) => {
	return data.map(item => ({
		...item,
		changeTypeLabel: item.changeType === ChangeType.ORG_CHANGE ? '单位变更' : '项目变更',
		changeTime: item.auditTime || '-',
		beforeInfo: getDictLabel(item.changeBefore, item.changeType),
		afterInfo: getDictLabel(item.changeAfter, item.changeType)
	}))
}

const tableData = ref<ChangeHistoryRecord[]>([])

// 监听数据变化
watch(
	() => props.athleteId,
	() => {
		tableData.value = transformerData(props.data)
	}
)
</script>

<template>
	<div class="change-history p-5 bg-primary rounded">
		<div class="flex justify-between items-center mb-4">
			<span class="font-semibold text-lg text-primary">变更历史</span>
		</div>

		<QTable
			:data="tableData"
			:columns="tableColumns"
			:loading="loading"
			:pagination="false"
		>
			<!-- 空状态插槽 -->
			<template #empty>
				<div class="py-8 text-center">
					<div class="text-tertiary text-14px">暂无变更历史记录</div>
				</div>
			</template>
		</QTable>
	</div>
</template>

<style scoped>
.change-history {
	/* 继承父级样式，保持一致 */
}
</style>
